"""
插件国际化支持系统
提供多语言支持和本地化资源管理
"""

import os
import json
import locale
from typing import Dict, Optional, Any
from pathlib import Path


class LocalizationManager:
    """本地化管理器"""
    
    def __init__(self, locales_dir: str = "./locales"):
        self.locales_dir = locales_dir
        self._translations: Dict[str, Dict[str, str]] = {}
        self._current_locale = self._detect_system_locale()
        self._load_translations()
    
    def _detect_system_locale(self) -> str:
        """检测系统语言环境"""
        try:
            # 获取系统默认语言
            system_locale = locale.getdefaultlocale()[0]
            if system_locale:
                # 转换为标准格式 (如 zh_CN, en_US)
                return system_locale.replace('-', '_')
        except:
            pass
        
        # 默认返回英语
        return "en_US"
    
    def _load_translations(self):
        """加载所有翻译文件"""
        if not os.path.exists(self.locales_dir):
            return
        
        for filename in os.listdir(self.locales_dir):
            if filename.endswith('.json'):
                locale_code = filename[:-5]  # 移除 .json 后缀
                file_path = os.path.join(self.locales_dir, filename)
                
                try:
                    with open(file_path, 'r', encoding='utf-8') as f:
                        self._translations[locale_code] = json.load(f)
                except Exception as e:
                    print(f"Error loading translation file {filename}: {e}")
    
    def set_locale(self, locale_code: str):
        """设置当前语言环境"""
        self._current_locale = locale_code
    
    def get_locale(self) -> str:
        """获取当前语言环境"""
        return self._current_locale
    
    def get_available_locales(self) -> list[str]:
        """获取可用的语言环境"""
        return list(self._translations.keys())
    
    def translate(self, key: str, locale_code: Optional[str] = None, **kwargs) -> str:
        """翻译文本"""
        if locale_code is None:
            locale_code = self._current_locale
        
        # 查找翻译
        translation = self._translations.get(locale_code, {}).get(key, key)
        
        # 处理占位符
        if kwargs:
            try:
                translation = translation.format(**kwargs)
            except:
                pass
        
        return translation
    
    def add_translation(self, locale_code: str, translations: Dict[str, str]):
        """添加翻译"""
        if locale_code not in self._translations:
            self._translations[locale_code] = {}
        
        self._translations[locale_code].update(translations)
    
    def save_translations(self, locale_code: str, file_path: Optional[str] = None):
        """保存翻译到文件"""
        if file_path is None:
            file_path = os.path.join(self.locales_dir, f"{locale_code}.json")
        
        if locale_code in self._translations:
            os.makedirs(os.path.dirname(file_path), exist_ok=True)
            with open(file_path, 'w', encoding='utf-8') as f:
                json.dump(self._translations[locale_code], f, ensure_ascii=False, indent=2)


class PluginLocalization:
    """插件本地化支持"""
    
    def __init__(self, plugin_name: str, localization_manager: LocalizationManager):
        self.plugin_name = plugin_name
        self.localization_manager = localization_manager
        self._plugin_locales_dir = None
    
    def set_plugin_locales_dir(self, locales_dir: str):
        """设置插件本地化文件目录"""
        self._plugin_locales_dir = locales_dir
        self._load_plugin_translations()
    
    def _load_plugin_translations(self):
        """加载插件特定的翻译文件"""
        if not self._plugin_locales_dir or not os.path.exists(self._plugin_locales_dir):
            return
        
        for filename in os.listdir(self._plugin_locales_dir):
            if filename.endswith('.json'):
                locale_code = filename[:-5]  # 移除 .json 后缀
                file_path = os.path.join(self._plugin_locales_dir, filename)
                
                try:
                    with open(file_path, 'r', encoding='utf-8') as f:
                        plugin_translations = json.load(f)
                    
                    # 为插件翻译添加前缀
                    prefixed_translations = {
                        f"{self.plugin_name}.{key}": value 
                        for key, value in plugin_translations.items()
                    }
                    
                    self.localization_manager.add_translation(locale_code, prefixed_translations)
                except Exception as e:
                    print(f"Error loading plugin translation file {filename}: {e}")
    
    def _(self, key: str, **kwargs) -> str:
        """翻译快捷方法"""
        return self.localization_manager.translate(key, **kwargs)
    
    def get_localized_resource(self, resource_name: str, locale_code: Optional[str] = None) -> Optional[str]:
        """获取本地化资源文件路径"""
        if locale_code is None:
            locale_code = self.localization_manager.get_locale()
        
        if self._plugin_locales_dir:
            # 尝试查找特定语言的资源
            localized_resource = os.path.join(self._plugin_locales_dir, locale_code, resource_name)
            if os.path.exists(localized_resource):
                return localized_resource
            
            # 尝试查找默认资源
            default_resource = os.path.join(self._plugin_locales_dir, resource_name)
            if os.path.exists(default_resource):
                return default_resource
        
        return None


# 预定义的语言环境
SUPPORTED_LOCALES = {
    'en_US': 'English (United States)',
    'zh_CN': '中文 (简体)',
    'zh_TW': '中文 (繁體)',
    'ja_JP': '日本語',
    'ko_KR': '한국어',
    'es_ES': 'Español',
    'fr_FR': 'Français',
    'de_DE': 'Deutsch',
    'ru_RU': 'Русский',
    'ar_SA': 'العربية'
}


def create_default_locales(locales_dir: str = "./locales"):
    """创建默认的本地化文件"""
    os.makedirs(locales_dir, exist_ok=True)
    
    # 英语
    en_translations = {
        "plugin_loaded": "Plugin loaded successfully",
        "plugin_unloaded": "Plugin unloaded successfully",
        "plugin_error": "Error in plugin: {error}",
        "file_access_denied": "Access to file denied: {path}",
        "network_access_denied": "Network access denied",
        "invalid_signature": "Invalid plugin signature",
        "update_available": "Update available for plugin: {plugin_name}",
        "update_installed": "Update installed successfully",
        "plugin_installed": "Plugin installed successfully"
    }
    
    # 简体中文
    zh_cn_translations = {
        "plugin_loaded": "插件加载成功",
        "plugin_unloaded": "插件卸载成功",
        "plugin_error": "插件错误: {error}",
        "file_access_denied": "文件访问被拒绝: {path}",
        "network_access_denied": "网络访问被拒绝",
        "invalid_signature": "插件签名无效",
        "update_available": "插件有可用更新: {plugin_name}",
        "update_installed": "更新安装成功",
        "plugin_installed": "插件安装成功"
    }
    
    # 保存翻译文件
    with open(os.path.join(locales_dir, "en_US.json"), 'w', encoding='utf-8') as f:
        json.dump(en_translations, f, ensure_ascii=False, indent=2)
    
    with open(os.path.join(locales_dir, "zh_CN.json"), 'w', encoding='utf-8') as f:
        json.dump(zh_cn_translations, f, ensure_ascii=False, indent=2)


# 使用示例
if __name__ == "__main__":
    # 创建默认本地化文件
    create_default_locales()
    
    # 创建本地化管理器
    loc_manager = LocalizationManager("./locales")
    
    # 测试翻译
    print(loc_manager.translate("plugin_loaded"))
    loc_manager.set_locale("zh_CN")
    print(loc_manager.translate("plugin_loaded"))